package userDao.UserDbConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDbconnection {
	private static final String USER = "root";
	private static final String PASSWORD = "123456";
	private static final String PARAMETER8 = "characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8"; //Mysql8以上版本连接参数需设置时区
	private static final String URL = "jdbc:mysql://localhost:3306/contactsdb?"+ PARAMETER8;
	private static Connection conn;
	
	/**
	 * 获得一个数据库连接对象
	 * @return java.sql.Connection实例
	 */
	public static Connection getConnection() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver"); //mysql8注册驱动，不建议省略
			if (conn == null||conn.isClosed()) {
				conn = DriverManager.getConnection(URL, USER, PASSWORD);
			} else {
				return conn;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	public static void close(ResultSet rs,PreparedStatement ps){
		try {
		if(ps!=null) {
			ps.close();
			ps=null;
		}
		if(rs!=null) {
			rs.close();
			rs=null;
		}
		conn.close();
		}
		catch(SQLException e) {
			
		}
	}
}
